package cn.itcast.web.exceptions;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
    自定义异常处理器的步骤：
        1. 自定义一个类实现HandlerExceptionResolver接口
        2. 实现接口中的方法
        3. 创建异常处理器的对象
 */
@Component
public class CustomerExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                         Object o, Exception e) {

        //1. 创建ModelAndView对象
        ModelAndView mv = new ModelAndView();
        if (e.getClass().toString().contains("UnauthorizedException")) {
            mv.setViewName("forward:/unauthorized.jsp");
            return mv;
        }
        //2. 保存异常信息到ModelAndView里面
        mv.addObject("errorMsg",e.getMessage());
        //3. 设置返回的视图页面名称
        mv.setViewName("error");
        return mv;
    }
}
